package com.haoze.nurse.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.DateUtil;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurse.config.MinioConfig;
import com.haoze.nurse.dao.PatChapTempLogMapper;
import com.haoze.nurse.dao.PatChaperonageMapper;
import com.haoze.nurse.enumeration.FileTypeEnum;
import com.haoze.nurse.model.PatChapTempLogEntity;
import com.haoze.nurse.model.PatChaperonageEntity;
import com.haoze.nurse.params.ChapApproveParam;
import com.haoze.nurse.params.ChapTempParam;
import com.haoze.nurse.params.ChaperonageParam;
import com.haoze.nurse.service.ChaperonageService;
import com.haoze.nurse.utils.ExcelUtil;
import com.haoze.nurse.utils.MinioUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class ChaperonageServiceImpl implements ChaperonageService {
    private final Logger logger = LoggerFactory.getLogger(ChaperonageServiceImpl.class);
    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioConfig minioConfig;
    @Resource
    private PatChaperonageMapper patChaperonageMapper;
    @Resource
    private PatChapTempLogMapper patChapTempLogMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addChaperonage(ChaperonageParam param) {

        if (!(param.getSiftItem01().equals("0")
                &&param.getSiftItem02().equals("0")
                &&param.getSiftItem03().equals("0")
                &&param.getSiftItem04().equals("0")
                &&param.getSiftItem05().equals("0")
                &&param.getSiftItem06().equals("0")
                &&param.getSiftItem07().equals("0"))) {
            return ResultGenerator.genFailedResult("陪护登记疫情筛查记录异常，审核未通过！");
        }

        if (param.getInputType().equals("0")) { // 互联网医院入口提交申请
            // 七日内核酸检测结果判断(如果有检验结果，获取检验结果中的lab_date作为checkDate, 如果没有去申请时间作为checkDate)
            Map<String, String> ncovReport = patChaperonageMapper.queryNcovReport(param.getIdNum());

            if (ncovReport!=null) { // 做了检测
                // checkDate", t3.report_result "reportResult"
                String beginLab = DateUtil.dateToString(
                        DateUtil.getTargetDate(new Date(), 0, 0, -7, 0, 0, 0), "yyyy-MM-dd");
                if (ncovReport.get("checkDate").compareTo(beginLab) >= 0) { // 未超过七天
                    // 获取当前序号
                    Integer chapNo = patChaperonageMapper.selectLastChapNo(param.getInpatNum());
                    chapNo = chapNo==null ? 1 : chapNo+1;

                    PatChaperonageEntity patChaperonageEntity = new PatChaperonageEntity();

                    patChaperonageEntity.setChapId(UUIDUtil.randomString());
                    patChaperonageEntity.setDataVersion(1);
                    patChaperonageEntity.setGmtCreate(new Date());
                    patChaperonageEntity.setGmtModify(new Date());
                    patChaperonageEntity.setDelFlag("0");
                    patChaperonageEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                    patChaperonageEntity.setChapNo(chapNo);
                    patChaperonageEntity.setApproveStatus("0");
                    patChaperonageEntity.setIdNum(param.getIdNum());
                    patChaperonageEntity.setInpatNum(param.getInpatNum());
                    patChaperonageEntity.setInputType(param.getInputType());
                    patChaperonageEntity.setNucleinImg(param.getNucleinImg());
                    patChaperonageEntity.setUserIcon(param.getUserIcon());
                    patChaperonageEntity.setPhone(param.getPhone());
                    patChaperonageEntity.setSiftItem01(param.getSiftItem01());
                    patChaperonageEntity.setSiftItem02(param.getSiftItem02());
                    patChaperonageEntity.setSiftItem03(param.getSiftItem03());
                    patChaperonageEntity.setSiftItem04(param.getSiftItem04());
                    patChaperonageEntity.setSiftItem05(param.getSiftItem05());
                    patChaperonageEntity.setSiftItem06(param.getSiftItem06());
                    patChaperonageEntity.setSiftItem07(param.getSiftItem07());
                    patChaperonageEntity.setUserName(param.getUserName());
                    patChaperonageEntity.setAskType("0");
                    patChaperonageEntity.setCheckTime(DateUtil.stringToDate(ncovReport.get("checkTime"), "yyyy-MM-dd HH:mm:ss"));
                    // 七日内做了检测序号为1且非异常结果则默认通过审批
                    if (StringUtils.isBlank(ncovReport.get("reportResult"))) { // 七日内进行了检测但是未出结果
                        patChaperonageEntity.setRecordStatus("0");
                        if (chapNo==1) {
                            patChaperonageEntity.setApproveStatus("1");
                            patChaperonageMapper.insert(patChaperonageEntity);
                            return ResultGenerator.genOkResult("陪护人信息登记/修改成功，系统已审核通过，请在住院陪护界面查询电子陪护卡！");
                        } else {
                            patChaperonageMapper.insert(patChaperonageEntity);
                            return ResultGenerator.genOkResult("陪护登记已提交，请到护士站告知护士审核，审核通过后可领取电子陪护卡！");
                        }


                    } else if (ncovReport.get("reportResult").equals("未检出") || ncovReport.get("reportResult").equals("阴性")) { // 七日内进行了检测且未检出
                        patChaperonageEntity.setRecordStatus("1");
                        if (chapNo==1) {
                            patChaperonageEntity.setApproveStatus("1");
                            patChaperonageMapper.insert(patChaperonageEntity);
                            return ResultGenerator.genOkResult("陪护人信息登记/修改成功，系统已审核通过，请在住院陪护界面查询电子陪护卡！");
                        } else {
                            patChaperonageMapper.insert(patChaperonageEntity);
                            return ResultGenerator.genOkResult("陪护登记已提交，请到护士站告知护士审核，审核通过后可领取电子陪护卡！");
                        }

                    } else {
                        return ResultGenerator.genFailedResult("陪护人7日内核酸检测结果为阳性，审核未通过！");
                    }
                }
            }

            // 未做检测和检测超过七天情况执行以下逻辑
            // 他院核酸检测报告必填
            if (StringUtils.isBlank(param.getNucleinImg())) {
                return ResultGenerator.genFailedResult("七日内未在本院做过核酸检测，请上传他院核酸检测报告");
            }

            // 获取当前序号
            Integer chapNo = patChaperonageMapper.selectLastChapNo(param.getInpatNum());
            chapNo = chapNo==null ? 1 : chapNo+1;
            PatChaperonageEntity patChaperonageEntity = new PatChaperonageEntity();
            patChaperonageEntity.setChapId(UUIDUtil.randomString());
            patChaperonageEntity.setDataVersion(1);
            patChaperonageEntity.setGmtCreate(new Date());
            patChaperonageEntity.setGmtModify(new Date());
            patChaperonageEntity.setDelFlag("0");
            patChaperonageEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
            patChaperonageEntity.setChapNo(chapNo);
            patChaperonageEntity.setApproveStatus("0");
            patChaperonageEntity.setIdNum(param.getIdNum());
            patChaperonageEntity.setInpatNum(param.getInpatNum());
            patChaperonageEntity.setInputType(param.getInputType());
            patChaperonageEntity.setNucleinImg(param.getNucleinImg());
            patChaperonageEntity.setUserIcon(param.getUserIcon());
            patChaperonageEntity.setPhone(param.getPhone());
            patChaperonageEntity.setSiftItem01(param.getSiftItem01());
            patChaperonageEntity.setSiftItem02(param.getSiftItem02());
            patChaperonageEntity.setSiftItem03(param.getSiftItem03());
            patChaperonageEntity.setSiftItem04(param.getSiftItem04());
            patChaperonageEntity.setSiftItem05(param.getSiftItem05());
            patChaperonageEntity.setSiftItem06(param.getSiftItem06());
            patChaperonageEntity.setSiftItem07(param.getSiftItem07());
            patChaperonageEntity.setUserName(param.getUserName());
            patChaperonageEntity.setAskType("1");
            patChaperonageMapper.insert(patChaperonageEntity);

            return ResultGenerator.genOkResult("陪护登记已提交，请到护士站告知护士审核，审核通过后可领取电子陪护卡！");

        } else { // 护士手动录入
            // 获取当前序号
            Integer chapNo = patChaperonageMapper.selectLastChapNo(param.getInpatNum());
            chapNo = chapNo==null ? 1 : chapNo+1;
            PatChaperonageEntity patChaperonageEntity = new PatChaperonageEntity();
            patChaperonageEntity.setChapId(UUIDUtil.randomString());
            patChaperonageEntity.setDataVersion(1);
            patChaperonageEntity.setGmtCreate(new Date());
            patChaperonageEntity.setGmtModify(new Date());
            patChaperonageEntity.setDelFlag("0");
            patChaperonageEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
            patChaperonageEntity.setChapNo(chapNo);
            patChaperonageEntity.setApproveStatus("0");
            patChaperonageEntity.setIdNum(param.getIdNum());
            patChaperonageEntity.setInpatNum(param.getInpatNum());
            patChaperonageEntity.setInputType(param.getInputType());
            patChaperonageEntity.setNucleinImg(param.getNucleinImg());
            patChaperonageEntity.setUserIcon(param.getUserIcon());
            patChaperonageEntity.setPhone(param.getPhone());
            patChaperonageEntity.setSiftItem01(param.getSiftItem01());
            patChaperonageEntity.setSiftItem02(param.getSiftItem02());
            patChaperonageEntity.setSiftItem03(param.getSiftItem03());
            patChaperonageEntity.setSiftItem04(param.getSiftItem04());
            patChaperonageEntity.setSiftItem05(param.getSiftItem05());
            patChaperonageEntity.setSiftItem06(param.getSiftItem06());
            patChaperonageEntity.setSiftItem07(param.getSiftItem07());
            patChaperonageEntity.setUserName(param.getUserName());
            // 护士录入默认通过
            patChaperonageEntity.setApproveStatus("1");

            patChaperonageMapper.insert(patChaperonageEntity);
            return ResultGenerator.genOkResult("陪护信息已录入");

        }
    }

    @Override
    public Result chaperonageList(Integer page, Integer pageSize, String wardId, String beginTime, String endTime) {
        if (StringUtils.isBlank(beginTime)) {
            // 如果起始时间为空则设置为前一日0点
            beginTime = DateUtil.dateToString(DateUtil.getTargetDate(new Date(), 0,0,-1,0,0,0), "yyyy-MM-dd");
        }
        if (StringUtils.isBlank(endTime)) {
            // 如果截止时间为空则设置为当前时间
            endTime = DateUtil.dateToString(new Date(), "yyyy-MM-dd");
        }

        PageHelper.startPage(page, pageSize);
        List<Map<String, Object>> list = patChaperonageMapper.selectChapList(wardId, beginTime, endTime);
        return ResultGenerator.genOkResult(PageInfo.of(list));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result approveChap(ChapApproveParam param) {
        if (param.getApproveStatus().equals("1")) {
            // 通过申请
            Map<String, String> currentUser = getCurrentUser();
            PatChaperonageEntity patChaperonageEntity = new PatChaperonageEntity();
            patChaperonageEntity.setChapId(param.getChapId());
            patChaperonageEntity.setApproveUserId(currentUser.get("userId"));
            patChaperonageEntity.setApproveStatus(param.getApproveStatus());
            patChaperonageEntity.setApproveUserName(currentUser.get("userName"));
            patChaperonageEntity.setRejectReason(param.getRejectReason());
            patChaperonageEntity.setApproveTime(new Date());
            patChaperonageEntity.setGmtModify(new Date());
            patChaperonageMapper.updateByPrimaryKeySelective(patChaperonageEntity);
            // 重新对编号排序
            patChaperonageMapper.updateAllPassAndUnapprove(param.getChapId());

            return ResultGenerator.genOkResult("审批通过");
        } else if (param.getApproveStatus().equals("2")) {
            // 驳回申请
            Map<String, String> currentUser = getCurrentUser();
            PatChaperonageEntity patChaperonageEntity = new PatChaperonageEntity();
            patChaperonageEntity.setChapId(param.getChapId());
            patChaperonageEntity.setApproveUserId(currentUser.get("userId"));
            patChaperonageEntity.setApproveStatus(param.getApproveStatus());
            patChaperonageEntity.setApproveUserName(currentUser.get("userName"));
            patChaperonageEntity.setRejectReason(param.getRejectReason());
            patChaperonageEntity.setApproveTime(new Date());
            patChaperonageEntity.setGmtModify(new Date());
            patChaperonageMapper.updateByPrimaryKeySelective(patChaperonageEntity);
            // 重新对编号排序
            patChaperonageMapper.updateAllPassAndUnapprove(param.getChapId());
            return ResultGenerator.genOkResult("驳回完成");
        } else {
            return ResultGenerator.genFailedResult("未知的审批状态");
        }

    }

    @Override
    public Result patientInfo(String inpatNum, String patName) {
        // 判断患者是否开立过陪护医嘱
        Integer count = patChaperonageMapper.selectChapOrder(inpatNum, patName);
        if (count==null || count==0) {
            return ResultGenerator.genFailedResult("当前患者无正在执行的陪护医嘱，无法创建陪护申请");
        }
        Map<String, Object> map = patChaperonageMapper.selectPatientInfo(inpatNum);
        if (MapUtils.isEmpty(map)) {
            return ResultGenerator.genFailedResult("未找到此住院号对应的患者");
        }
        if (map.get("outDatetime")!=null) {
            return ResultGenerator.genFailedResult("该患者已经出院");
        }
        return ResultGenerator.genOkResult(map);
    }

    @Override
    public Result chapNo(String inpatNum) {
        Integer chapNo = patChaperonageMapper.selectLastChapNo(inpatNum);
        chapNo = chapNo==null ? 1 : chapNo+1;
        return ResultGenerator.genOkResult(chapNo);
    }

    @Override
    public Result chapList(String idNum) {
        List<Map<String, Object>> maps = patChaperonageMapper.selectUserChapList(idNum);
        return ResultGenerator.genOkResult(maps);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result changePhone(ChaperonageParam param) {
        PatChaperonageEntity patChaperonageEntity = new PatChaperonageEntity();
        patChaperonageEntity.setChapId(param.getChapId());
        patChaperonageEntity.setGmtModify(new Date());
        patChaperonageEntity.setPhone(param.getPhone());
        patChaperonageMapper.updateByPrimaryKeySelective(patChaperonageEntity);
        return ResultGenerator.genOkResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result editChaperonage(ChaperonageParam param) {
        // 未审核he驳回的的可以修改所有申请人信息，审核通过的只可以修改手机号
        PatChaperonageEntity patChaperonageEntity = patChaperonageMapper.selectByPrimaryKey(param.getChapId());

        if (patChaperonageEntity.getApproveStatus().equals("0")) {
            // 未审核
            if (!(param.getSiftItem01().equals("0")
                    &&param.getSiftItem02().equals("0")
                    &&param.getSiftItem03().equals("0")
                    &&param.getSiftItem04().equals("0")
                    &&param.getSiftItem05().equals("0")
                    &&param.getSiftItem06().equals("0")
                    &&param.getSiftItem07().equals("0"))) {
                return ResultGenerator.genFailedResult("陪护登记疫情筛查记录异常，审核未通过！");
            }

            // 七日内核酸检测结果判断
            Map<String, String> ncovReport = patChaperonageMapper.queryNcovReport(param.getIdNum());

            if (ncovReport!=null) { // 做了检测
                // checkDate", t3.report_result "reportResult"
                String beginLab = DateUtil.dateToString(
                        DateUtil.getTargetDate(new Date(), 0, 0, -7, 0, 0, 0), "yyyy-MM-dd");
                if (ncovReport.get("checkDate").compareTo(beginLab) >= 0) { // 未超过七天
                    // 获取当前序号

                    patChaperonageEntity.setDataVersion(patChaperonageEntity.getDataVersion()+1);
                    patChaperonageEntity.setGmtModify(new Date());
                    patChaperonageEntity.setDelFlag("0");
                    patChaperonageEntity.setApproveStatus("0");
                    patChaperonageEntity.setIdNum(param.getIdNum());
                    patChaperonageEntity.setInpatNum(param.getInpatNum());
                    patChaperonageEntity.setInputType(param.getInputType());
                    patChaperonageEntity.setNucleinImg(param.getNucleinImg());
                    patChaperonageEntity.setUserIcon(param.getUserIcon());
                    patChaperonageEntity.setPhone(param.getPhone());
                    patChaperonageEntity.setSiftItem01(param.getSiftItem01());
                    patChaperonageEntity.setSiftItem02(param.getSiftItem02());
                    patChaperonageEntity.setSiftItem03(param.getSiftItem03());
                    patChaperonageEntity.setSiftItem04(param.getSiftItem04());
                    patChaperonageEntity.setSiftItem05(param.getSiftItem05());
                    patChaperonageEntity.setSiftItem06(param.getSiftItem06());
                    patChaperonageEntity.setSiftItem07(param.getSiftItem07());
                    patChaperonageEntity.setUserName(param.getUserName());
                    patChaperonageEntity.setAskType("0");
                    patChaperonageEntity.setCheckTime(DateUtil.stringToDate(ncovReport.get("checkTime"), "yyyy-MM-dd HH:mm:ss"));
                    // 七日内做了检测序号为1且非异常结果则默认通过审批
                    if (StringUtils.isBlank(ncovReport.get("reportResult"))) { // 七日内进行了检测但是未出结果
                        patChaperonageEntity.setRecordStatus("0");
                        if (patChaperonageEntity.getChapNo()==1) {
                            patChaperonageEntity.setApproveStatus("1");
                            patChaperonageMapper.updateByPrimaryKeySelective(patChaperonageEntity);
                            return ResultGenerator.genOkResult("陪护人信息登记/修改成功，系统已审核通过，请在住院陪护界面查询电子陪护卡！");
                        } else {
                            patChaperonageMapper.updateByPrimaryKeySelective(patChaperonageEntity);
                            return ResultGenerator.genOkResult("陪护登记已提交，请到护士站告知护士审核，审核通过后可领取电子陪护卡！");
                        }


                    } else if (ncovReport.get("reportResult").equals("未检出") || ncovReport.get("reportResult").equals("阴性")) { // 七日内进行了检测且未检出
                        patChaperonageEntity.setRecordStatus("1");
                        if (patChaperonageEntity.getChapNo()==1) {
                            patChaperonageEntity.setApproveStatus("1");
                            patChaperonageMapper.updateByPrimaryKeySelective(patChaperonageEntity);
                            return ResultGenerator.genOkResult("陪护人信息登记/修改成功，系统已审核通过，请在住院陪护界面查询电子陪护卡！");
                        } else {
                            patChaperonageMapper.updateByPrimaryKeySelective(patChaperonageEntity);
                            return ResultGenerator.genOkResult("陪护登记已提交，请到护士站告知护士审核，审核通过后可领取电子陪护卡！");
                        }

                    } else {
                        return ResultGenerator.genFailedResult("陪护人7日内核酸检测结果为阳性，审核未通过！");
                    }
                }
            }

            // 未做检测和检测超过七天情况执行以下逻辑
            // 他院核酸检测报告必填
            if (StringUtils.isBlank(param.getNucleinImg())) {
                return ResultGenerator.genFailedResult("七日内未在本院做过核酸检测，请上传他院核酸检测报告");
            }

            // 获取当前序号

            patChaperonageEntity.setDataVersion(patChaperonageEntity.getDataVersion());
            patChaperonageEntity.setGmtModify(new Date());
            patChaperonageEntity.setDelFlag("0");
            patChaperonageEntity.setApproveStatus("0");
            patChaperonageEntity.setIdNum(param.getIdNum());
            patChaperonageEntity.setInpatNum(param.getInpatNum());
            patChaperonageEntity.setInputType(param.getInputType());
            patChaperonageEntity.setNucleinImg(param.getNucleinImg());
            patChaperonageEntity.setUserIcon(param.getUserIcon());
            patChaperonageEntity.setPhone(param.getPhone());
            patChaperonageEntity.setSiftItem01(param.getSiftItem01());
            patChaperonageEntity.setSiftItem02(param.getSiftItem02());
            patChaperonageEntity.setSiftItem03(param.getSiftItem03());
            patChaperonageEntity.setSiftItem04(param.getSiftItem04());
            patChaperonageEntity.setSiftItem05(param.getSiftItem05());
            patChaperonageEntity.setSiftItem06(param.getSiftItem06());
            patChaperonageEntity.setSiftItem07(param.getSiftItem07());
            patChaperonageEntity.setUserName(param.getUserName());
            patChaperonageEntity.setAskType("1");
            patChaperonageMapper.updateByPrimaryKeySelective(patChaperonageEntity);

            return ResultGenerator.genOkResult("陪护登记已提交，请到护士站告知护士审核，审核通过后可领取电子陪护卡！");
        } else if (patChaperonageEntity.getApproveStatus().equals("1")) {
            // 已通过
            patChaperonageEntity.setPhone(param.getPhone());
            patChaperonageEntity.setDataVersion(patChaperonageEntity.getDataVersion()+1);
            patChaperonageEntity.setGmtModify(new Date());
            patChaperonageMapper.updateByPrimaryKeySelective(patChaperonageEntity);
            return ResultGenerator.genOkResult();
        } else {
            // 申请已驳回，请重新提交申请
            return ResultGenerator.genFailedResult("申请已驳回，请重新提交申请");
        }
    }

    @Override
    public Result delChap(String chapId) {
        PatChaperonageEntity patChaperonageEntity = new PatChaperonageEntity();
        patChaperonageEntity.setGmtModify(new Date());
        patChaperonageEntity.setDelFlag("1");
        patChaperonageEntity.setChapId(chapId);
        patChaperonageMapper.updateByPrimaryKeySelective(patChaperonageEntity);
        return ResultGenerator.genOkResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addChapTemp(ChapTempParam param) {
        // 1、更新当天历史体温记录未删除状态
        patChapTempLogMapper.delTodayTemperatures(param.getChapId(), DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
        // 2、新增一条体温记录
        Map<String, String> currentUser = getCurrentUser();
        PatChapTempLogEntity patChapTempLogEntity = new PatChapTempLogEntity();
        patChapTempLogEntity.setChapTempId(UUIDUtil.randomString());
        patChapTempLogEntity.setChapId(param.getChapId());
        patChapTempLogEntity.setDataVersion(1);
        patChapTempLogEntity.setGmtCreate(new Date());
        patChapTempLogEntity.setGmtModify(new Date());
        patChapTempLogEntity.setRecordUserId(currentUser.get("userId"));
        patChapTempLogEntity.setRecordUserName(currentUser.get("userName"));
        patChapTempLogEntity.setTemperature(param.getTemperature());
        patChapTempLogEntity.setDelFlag("0");
        patChapTempLogMapper.insert(patChapTempLogEntity);
        return ResultGenerator.genOkResult(patChapTempLogEntity.getChapTempId());
    }

    @Override
    public Result delChapTemp(String chapTempId) {
        Map<String, String> currentUser = getCurrentUser();
        PatChapTempLogEntity patChapTempLogEntity = new PatChapTempLogEntity();
        patChapTempLogEntity.setChapTempId(chapTempId);
        patChapTempLogEntity.setGmtModify(new Date());
        patChapTempLogEntity.setDelFlag("1");
        patChapTempLogEntity.setDelUserId(currentUser.get("userId"));
        patChapTempLogMapper.updateByPrimaryKeySelective(patChapTempLogEntity);
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result chapStatus() {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, String>> inCountList = patChaperonageMapper.queryInHospitalCount();
        AtomicReference<Integer> patCount01 = new AtomicReference<>(0);
        AtomicReference<Integer> patCount02 = new AtomicReference<>(0);
        inCountList.stream().forEach(inCountMap -> {
            if (inCountMap.get("deptArea").equals("01")) {
                // 城中
                patCount01.set(Integer.valueOf(inCountMap.get("areaCount")));
            } else if (inCountMap.get("deptArea").equals("02")) {
                patCount02.set(Integer.valueOf(inCountMap.get("areaCount")));
            }
        });
        resultMap.put("patCount01", patCount01.get()); // 城中住院
        resultMap.put("patCount02", patCount02.get()); // 阳湖住院
        resultMap.put("patCount", patCount01.get()+patCount02.get()); // 全院住院

        List<Map<String, String>> chapCountList = patChaperonageMapper.queryInChapCount();
        AtomicReference<Integer> chapCount01 = new AtomicReference<>(0);
        AtomicReference<Integer> chapCount02 = new AtomicReference<>(0);
        AtomicReference<Integer> chapCount = new AtomicReference<>(0);
        chapCountList.stream().forEach(chapCountMap -> {
            if (chapCountMap.get("deptArea").equals("00")) {
                chapCount.set(Integer.valueOf(chapCountMap.get("areaCount")));
            } else if (chapCountMap.get("deptArea").equals("01")) {
                chapCount01.set(Integer.valueOf(chapCountMap.get("areaCount")));
            } else if (chapCountMap.get("deptArea").equals("02")) {
                chapCount02.set(Integer.valueOf(chapCountMap.get("areaCount")));
            }
        });

        resultMap.put("chapCount", chapCount.get());
        resultMap.put("chapCount01", chapCount01.get());
        resultMap.put("chapCount02", chapCount02.get());

        resultMap.put("inCount", chapCount.get()+patCount01.get()+patCount02.get());
        resultMap.put("inCount01", patCount01.get()+chapCount01.get());
        resultMap.put("inCount02", patCount02.get()+chapCount02.get());
        resultMap.put("comment", "patCount01:城中住院，patCount02:阳湖住院，patCount:住院全部；chapCount01:城中陪护，chapCount02:阳湖陪护，chapCount：陪护全部；inCount01:城中全部，inCount02:阳湖全部，inCount:全院全部");
        return ResultGenerator.genOkResult(resultMap);
    }

    @Override
    public Result tempHistory(String chapId, String beginDate, String endDate) {
        if (StringUtils.isBlank(beginDate)) {
            beginDate = "2020-01-01";
        }

        if (StringUtils.isBlank(endDate)) {
            endDate = DateUtil.dateToString(new Date(), "yyyy-MM-dd");
        }
        List<Map<String, Object>> list = patChapTempLogMapper.selectTempHistory(chapId, beginDate, endDate);
        return ResultGenerator.genOkResult(list);
    }

    @Override
    public Result oneChap(String chapId) {
        Map<String, Object> resultMap = new HashMap<>();
        PatChaperonageEntity patChaperonageEntity = patChaperonageMapper.selectByPrimaryKey(chapId);
        resultMap.put("patChap", patChaperonageEntity);
        Map<String, Object> map = patChaperonageMapper.selectPatientInfo(patChaperonageEntity.getInpatNum());
        resultMap.put("patInfo", map);
        return ResultGenerator.genOkResult(resultMap);
    }

    @Override
    public Result chapCardTempList(String wardId) {
        Integer patCount = patChaperonageMapper.queryInHospitalCountWithWardId(wardId);
        Integer chapCount = patChaperonageMapper.queryInChapCountWithWardId(wardId);

        List<Map<String, String>> list = patChaperonageMapper.chapCardList(wardId);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("patCount", patCount);
        resultMap.put("chapCount", chapCount);
        resultMap.put("list", list);
        return ResultGenerator.genOkResult(resultMap);
    }

    @Override
    public ResponseEntity<byte[]> exportTempExcel(String wardId, HttpServletResponse response) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = dateFormat.format(new Date());
        List<Map<String, String>> list = patChaperonageMapper.chapCardList(wardId);
        ResponseEntity<byte[]> res;
        res = getExcelHttpResponseEntity("chap_temp" + time + ".xls", ExcelUtil.exportChapTempExcel(list));
        return res;
    }

    @Override
    public Result getRoles() {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        List<Map<String, Object>> list = patChaperonageMapper.selectRoles(userId);
        return ResultGenerator.genOkResult(list);
    }

    private ResponseEntity<byte[]> getExcelHttpResponseEntity(String filename, byte[] body) {
        ResponseEntity.BodyBuilder res = ResponseEntity.status(HttpStatus.OK);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/vnd.ms-excel");
        headers.set("Content-Disposition", "attachment;filename=" + filename);
        return res.headers(headers).body(body);
    }

    private Map<String, String> getCurrentUser() {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        Map<String, String> currentUser = patChaperonageMapper.getUser(userId);
        if (currentUser == null)
            return new HashMap<String, String>();
        return currentUser;
    }
    @Override
    public Result uploadFile(MultipartFile file, String type) {
        FileTypeEnum typeEnum = null;
        for (FileTypeEnum enumTemp : FileTypeEnum.values()) {
            if (type.equals(enumTemp.getValue())) {
                typeEnum = enumTemp;
                break;
            }
        }
        if (typeEnum == null) {
            return ResultGenerator.genFailedResult("不支持的类型");
        }
        if (FileTypeEnum.FILE_TYPE_IMG.getType().equals(type)) {
            if ( file.getSize() > 1024 * 1024 * 10) {
                return ResultGenerator.genFailedResult("上传的原始图像大小不能超过10M");
            }
        }
        FileTypeEnum finalTypeEnum = typeEnum;
        try {
            String fileUUID = UUIDUtil.randomString();
            String filePath = finalTypeEnum.getPath() + fileUUID + MinioUtils.getSuffix(Objects.requireNonNull(file.getOriginalFilename()));
            minioClient.putObject(PutObjectArgs
                    .builder()
                    .bucket(minioConfig.getMinioBucket())
                    .object(filePath)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType("image/png") // 配置预览
                    .build());
            String fullFileUrl = minioConfig.getNginxUrl() + minioConfig.getMinioBucket() + "/" + filePath;

            Map<String, String> map = new HashMap<>();
            map.put("relativePath", minioConfig.getMinioBucket() + "/" + filePath);
            map.put("fileUrl", fullFileUrl);
            return ResultGenerator.genOkResult(map);
        } catch (Exception e) {
            logger.error("保存失败", e);

            return ResultGenerator.genFailedResult("保存失败");
        }
    }
}
